package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mainService.HTTPService;
import mainService.ServiceParams;
import mainService.data.IpClient;
import mainService.data.UsersConnected;
import mainService.data.Utente;
import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;

/**
 * Servizio di Login di un utente.
 * 
 * @author Daniel Procop, Mattia Grecchi
 */
public class LoginService implements HTTPService {

	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {

		String operatore = params.getValue("username");
		String password = params.getValue("password");

		
		IConnection manager = new ConnectionManager();
		manager.connect();

		Connection conn = manager.getConnection();

		try {
			Statement stmt = conn.createStatement();

			String qry = "SELECT username from users where username= '"
					+ operatore + " '";
			ResultSet rs = stmt.executeQuery(qry);

			if (!rs.first()) { // non registrato
				params.addParam("file", "nonRegistrato.html");
				return (new HttpFileServer()).getServiceResult(params);
			}

			qry = "SELECT username, role, id_project from users where username='"
					+ operatore + "' and password='" + password + "'";
			rs = stmt.executeQuery(qry);
			if (!rs.first()) { // password sbagliata
				params.addParam("file", "passwordErrata.html");
				return (new HttpFileServer()).getServiceResult(params);
			} else {
				operatore = rs.getString("username");
				String ruolo = rs.getString("role");
				int id_project = rs.getInt("id_project");
				Utente utente = new Utente(operatore, ruolo, id_project);
				UsersConnected.getUsersConnected().addUser(
						IpClient.getSingleton().getIp(), utente);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		params.addParam("file", "home.html");
		return (new HttpFileServer()).getServiceResult(params);
	}
}
